package com.example.autopia.view.Activities

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.View.OnScrollChangeListener
import android.view.ViewTreeObserver.OnScrollChangedListener
import android.widget.AbsListView
import android.widget.AbsListView.OnScrollListener
import android.widget.Toast
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SnapHelper
import com.example.autopia.R
import com.example.autopia.databinding.ActivityPaymentBinding
import com.example.autopia.model.Item.Card
import com.example.autopia.model.Item.News
import com.example.autopia.model.Item.Place
import com.example.autopia.model.Item.Transaction
import com.example.autopia.model.Item.User
import com.example.autopia.model.Repositories.ParkingRepository
import com.example.autopia.model.Repositories.TestRepository
import com.example.autopia.model.Repositories.TransactionRepository
import com.example.autopia.model.Repositories.UsersRepository
import com.example.autopia.utilities.TimeManager
import com.example.autopia.view.Adapters.CardAdapter
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase

class PaymentActivity : AppCompatActivity() {
    private lateinit var binding: ActivityPaymentBinding
    private val usersRepository = UsersRepository()
    private val transactionRepository = TransactionRepository()
    private val parkingRepository = ParkingRepository()
    private val adapter = CardAdapter()
    private val timeManager = TimeManager()

    private var c = 0
    private lateinit var user : User
    private lateinit var transaction : Transaction
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPaymentBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.CardList.adapter=adapter
        adapter.setData(TestRepository.getCardList())
        getUser()
        val snapHelper = LinearSnapHelper()
        snapHelper.attachToRecyclerView(binding.CardList)

        binding.CardList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            var isScrolling = false

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    isScrolling = false
                    val view = snapHelper.findSnapView(binding.CardList.layoutManager)
                    view?.let {
                        val k = binding.CardList.getChildAdapterPosition(it)
                        if (c != k) {
                            Log.d("Yatoro", k.toString())
                            c = k
                        }
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (dx != 0) {
                    isScrolling = true
                }
            }
        })

        binding.btBack.setOnClickListener {
            onBackPressed()
        }

        binding.btToCreate.setOnClickListener {
            startActivity(Intent(this@PaymentActivity, AddCardActivity::class.java))
        }
    }

    private fun getUser() {
        usersRepository.getUserById(Firebase.auth.currentUser?.uid ?: "").observe(this) { curUser ->
             user = curUser
            val cards = ArrayList<Card>()
            cards.add(Card("1", "", "", 111))
            if (!curUser.cardList.isNullOrEmpty()) {
                cards.addAll(curUser.cardList)
            } else {

            }
            adapter.setData(cards)
            binding.loading.visibility = View.GONE
            binding.CardList.visibility = View.VISIBLE
            getTransaction()
        }
    }
    private fun getTransaction(){
        transactionRepository.getActiveTransactionsByUserId(user.id).observe(this){
            transaction = it
            binding.tvTarif.text = transaction.price.toString() +" руб/час"
            binding.tvNumber.text = transaction.place?.car?.number?: "Ошибка"
            binding.tvStartTime.text = timeManager.unixTimeToDateTimeComment(transaction.startTime)
            val times = timeManager.getCurrentUnixTime()
            binding.tvEndTime.text = timeManager.unixTimeToDateTimeComment(times)
            binding.tvDelta.text =timeManager.formatSeconds((times-transaction.startTime).toLong())
            val parkCost = ((times-transaction.startTime)/60)*(transaction.price/60)
            binding.tvSum.text = parkCost.toString() +".00 руб."
            binding.tvFinnal.text = binding.tvSum.text
            binding.enter.setOnClickListener {
                if (parkCost<user.balance){
                    transaction.endTime=times
                    transaction.cardId = "balance"
                    transaction.active = false
                    usersRepository.removeBalance(user.id,parkCost)
                    transactionRepository.changeTransaction(transaction.id,transaction)
                    val place = Place(transaction.place!!.id,0,null,"nothing")
                    parkingRepository.changePlace(transaction.idPark, place.id,place)
                    Toast.makeText(this@PaymentActivity,"Парковка закончена",Toast.LENGTH_SHORT).show()
                    startActivity(Intent(this@PaymentActivity,MainActivity::class.java))
                }else{
                    Toast.makeText(this@PaymentActivity,"Недостаточно средств",Toast.LENGTH_SHORT)
                }
            }
        }
    }
}